package com.lyn.frp;

import android.os.Handler;
import android.os.Looper;
import android.util.Log;

import com.lyn.frp.listener.FrpListener;

import java.util.UUID;
import frpclib.Frpclib;

/**
 * frp 管理
 *
 * @author longyn 2024/01/22
 * @version 1.0.0
 */
public class FrpHelper {

    private final static String TAG = FrpHelper.class.getSimpleName();

    private final static Handler handler = new Handler(Looper.getMainLooper());
    private static boolean isRunning;

    private final static String uuid = UUID.randomUUID().toString().replace("-", "");

    private static FrpListener listener;

    public static void setListener(FrpListener listener) {
        FrpHelper.listener = listener;
    }

    private static FrpConfig frpConfig;

    public static FrpConfig getFrpConfig() {
        return frpConfig;
    }

    public static void connect(FrpConfig frpConfig) {
        if (isRunning) {
            return;
        }
        FrpHelper.frpConfig = frpConfig;
        new Thread(() -> {
            try {
                Log.d(TAG, "connect frpConfig:" + frpConfig.toString());
                isRunning = true;
                Frpclib.runContent(uuid, frpConfig.toString());
                if (listener != null) {
                    handler.post(() -> listener.onDisconnect());
                }
                Log.e(TAG, "frp end!");
            } catch (Throwable e) {
                e.printStackTrace();
            } finally {
                isRunning = false;
            }
        }).start();
    }

    public static void disconnect() {

        try {
            Frpclib.close(uuid);
        } catch (Throwable e) {
            e.printStackTrace();
        }
    }

    public static boolean isConnect() {
        return Frpclib.isRunning(uuid);
    }
}
